<template>
  <div class="header-wrapper">
    <div class="nav-placeholder"></div>
    <header class="header">
      <!-- 侧边导航 -->
      <SideNav ref="sideNavRef" />

      <!-- 全局导航栏 -->
      <div class="nav-belt">
        <div class="nav-left">
          <div class="nav-logo">
            <a href="/" class="nav-logo-link" aria-label="Amazon">
              <img src="@/assets/images/Amazon_logo.svg" alt="Amazon" class="amazon-logo" />
            </a>
          </div>
          <LocationDetector :default-location="$t('正在获取...')" />
        </div>

        <div class="nav-fill">
          <div class="nav-search">
            <div class="nav-search-select">
              <select>
                <option value="all">{{ $t('全部分类') }}</option>
                <option v-for="v in cartStore.fatherCategoryList" :key="v.id" :value="v.id">{{ v.name }}</option>
              </select>
              <i class="fas fa-caret-down"></i>
            </div>
            <el-select
              v-model="productName"
              filterable
              remote
              :placeholder="$t('搜索 Amazon 优惠券')"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in productOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click="handleProductSelect(item)"
              />
            </el-select>
<!--            <input type="text" class="nav-search-input" :placeholder="$t('搜索 Amazon 优惠券')">-->
            <button class="nav-search-submit">
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>

        <div class="nav-right">
          <!-- 语言选择 -->
          <div class="language-selector">
            <el-dropdown trigger="hover" @command="handleLanguageChange">
              <div class="language-display">
                <img
                  :src="langStore.languageIcon"
                  :alt="langStore.languageName"
                  class="flag-icon"
                />
                <span class="lang-text">{{ langStore.languageName }}</span>
                <i class="fas fa-caret-down"></i>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="lang in langStore.languageList"
                    :key="lang.id"
                    :command="lang.langKey"
                  >
                    <div class="lang-item">
                      <i
                        class="far"
                        :class="{
                          'fa-dot-circle': currentLang === lang.langKey,
                          'fa-circle': currentLang !== lang.langKey
                        }"
                      ></i>
                      <img
                        :src="lang.icon"
                        :alt="lang.countryName"
                        class="flag-icon"
                      />
                      <span>{{ lang.countryName }}</span>
                    </div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 账户信息 -->
          <AccountDropdown />

          <!-- 订单 -->
          <div class="nav-item hover-effect" @click="handleOrderClick">
            <div class="nav-line-1-2">
              <div class="text-xs text-white">{{ $t('退货') }}</div>
              <div class="text-md text-white font-bold">{{ $t('和订单') }}</div>
            </div>
          </div>

          <!-- 购物车 -->
          <div class="cart-link" @click="handleCartClick">
            <div class="nav-cart-wrapper">
              <div class="nav-cart-icon nav-sprite"></div>
              <span class="nav-cart-count">{{ cartStore.shopCartTotal }}</span>
            </div>
            <span class="text-sm text-white font-bold">{{ $t('购物车') }}</span>
          </div>
        </div>
      </div>

      <!-- 主导航栏 -->
      <div class="nav-main-wrapper" :class="{ 'nav-main-hidden': isHidden }">
        <nav class="nav-main">
          <!-- 左侧全部分类按钮 -->
          <button class="nav-all" @click="openSideNav">
            <i class="fas fa-bars"></i>
            <span>{{ $t('全部') }}</span>
          </button>

          <!-- 导航链接列表 -->
          <ul class="nav-list">
            <li>
              <router-link to="/deals" :class="{ 'active-link': activeMenu === '/deals' }">{{ $t('限时秒杀') }}</router-link>
            </li>
            
            <li v-for="v in cartStore.fatherCategoryList" :key="v.id">
              <router-link :to="`/products/category?catId=${v.catId}&name=${v.name}`" :class="{'active-link': activeMenu === `/products/category/${v.catId}`}">{{ v.name }}</router-link>
            </li>
            <li>
              <router-link to="/about-coupons" :class="{'active-link': activeMenu === '/about-coupons'}">{{ $t('关于优惠卷') }}</router-link>
            </li>
          </ul>
        </nav>
      </div>
    </header>
  </div>
</template>

<script setup>
// 导入必要的组件和工具
import {ref, onMounted, onUnmounted, watchEffect} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import SideNav from './SideNav.vue'
import LocationDetector from './LocationDetector.vue'
import AccountDropdown from './AccountDropdown.vue'
import useCartStore from "@/store/modules/cart";
import useLangStore from "@/store/modules/lang";
import useUserStore from "@/store/modules/user.js";
import {ApiCommodityList} from "@/api/commodity";
import {ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";
const { t } = useI18n();

const router = useRouter()                 // 路由实例
const route = useRoute()
const cartStore = useCartStore();
const langStore = useLangStore()
const userStore = useUserStore()

// 组件状态管理
const sideNavRef = ref() // 侧边导航栏引用
const currentLang = ref(langStore.language)    // 当前语言

const activeMenu = ref('')
watchEffect(() => {
  activeMenu.value = route.path + (route.query?.catId ? `/${route.query?.catId}` : '')
})

//搜索
const productName = ref('')
const productOptions = ref([])
const loading = ref(false)
const remoteMethod = (query) => {
  if (query) {
    loading.value = true
    const params = {
      pageNum: 1,
      type:0,
      pageSize: 1000000,
      productName: query
    }
    ApiCommodityList(params).then(res => {
      loading.value = false
      productOptions.value = res.rows.map(item => ({
        value: item.id,
        label: item.name,
        type: item.type
      }))
    })
  } else {
    productOptions.value = []
  }
}
const handleProductSelect = (item) => {
  productName.value = ''
  if(item.type == 0){
    router.push(`/products/detail/${item.value}`)
  }else{
    router.push(`/deals/${item.value}`)
  }
}


// 语言切换处理
const handleLanguageChange = (lang) => {
  langStore.setLanguage(lang).then(() => {
    currentLang.value = lang
    ElMessage({
      message: t('设置成功'),
      type: 'success',
      duration: 2000
    })
    
    setTimeout(() => {
      window.location.reload()
    }, 500)
  })
}

// 打开侧边导航栏
const openSideNav = () => {
  if (sideNavRef.value) {
    sideNavRef.value.open()
  }
}

// 导航栏滚动隐藏逻辑
const isHidden = ref(false)
let lastScrollTop = 0

// 滚动事件处理
const handleScroll = () => {
  const currentScrollTop = window.scrollY
  // 向下滚动超过100px时隐藏导航栏
  if (currentScrollTop > lastScrollTop && currentScrollTop > 100) {
    isHidden.value = true
  } else {
    isHidden.value = false
  }
  lastScrollTop = currentScrollTop
}

// 生命周期钩子
onMounted(() => {
  // 添加滚动监听
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  // 移除滚动监听
  window.removeEventListener('scroll', handleScroll)
})

// 订单按钮点击处理
const handleOrderClick = () => {
  if (!userStore.isLogin) {
    router.push('/login')  // 未登录跳转登录页
  } else {
    router.push('/account/orders')  // 已登录跳转订单页
  }
}

// 购物车按钮点击处理
const handleCartClick = () => {
  if (!userStore.isLogin) {
    router.push('/login')  // 未登录跳转登录页
  } else {
    router.push('/products/cart')  // 已登录跳转购物车页
  }
}
</script>

<style lang="scss" scoped>
@use '@/styles/components/header.scss' as *;

.header-wrapper {
  position: relative;
  width: 100%;
}

.nav-placeholder {
  height: 99px; // PC端导航占位
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: $primary-color;
  width: 100%;
}

::v-deep{
  .el-select__wrapper{
    height: 40px;
    line-height: 40px;
    box-shadow: none;
    border-radius: 0px;
  }
  .el-select__input:focus{
    outline: none;
    outline-offset: 0px;
  }

}
</style>
